package com.unitechs.commons.utils;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Map工具类
 * @author ZhouYz
 * @since 1.0.0
 */
@Slf4j
public final class ZyucMapUtil {
    private ZyucMapUtil() {
        //防止实例化
        throw new AssertionError();
    }

    /**
     * 将Set集合或者List集合，根据某个属性换为Map
     * @param collection 集合
     * @param propertyName 属性名
     */
    public static <T, K> Map<K, T> zyucSetCollectionToMap(Collection<T> collection, String propertyName) {
        Map<K, T> map = new HashMap<>();
        if (collection == null || collection.isEmpty()) {
            return map;
        }
        try {
            for (T item : collection) {
                Method getter = getGetterMethod(item.getClass(), propertyName);
                if (getter != null) {
                    @SuppressWarnings("unchecked")
                    K key = (K) getter.invoke(item);
                    map.put(key, item);
                }
            }
        } catch (Exception e) {
            log.info("对象转Map时发生了错误，请检查传入的参数是否符合要求。");
        }
        return map;
    }

    private static Method getGetterMethod(Class<?> clazz, String propertyName) {
        String getterName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        try {
            return clazz.getMethod(getterName);
        } catch (NoSuchMethodException e) {
            return null; // 没有找到匹配的 getter 方法
        }
    }

}
